package com.cib.icarus.desensitize.wrapper.internals;


import com.cib.icarus.core.utils.ClassUtils;
import com.cib.icarus.desensitize.wrapper.DesAbstractWrapper;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author goomba
 */
public class JacksonDesWrapper extends DesAbstractWrapper {

    private static final Logger logger = LoggerFactory.getLogger(JacksonDesWrapper.class);

    private final ObjectMapper mapper;

    public JacksonDesWrapper() {
        this(null);
    }

    public JacksonDesWrapper(Include include) {
        this.mapper = new ObjectMapper();
        // 设置输出时包含属性的风格
        if (include != null) {
            this.mapper.setSerializationInclusion(include);
        }
        // 设置输入时忽略在JSON字符串中存在但Java对象实际没有的属性
        this.mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
    }

    public static JacksonDesWrapper nonNullMapper() {
        return new JacksonDesWrapper(Include.NON_NULL);
    }

    @Override
    public String showAsString(Object source) {
        try {
            return this.mapper.writeValueAsString(desensitize(source));
        } catch (Exception e) {
            logger.warn("try to write {} desensitize json occur error {}!!!, will return toString", source, e.getMessage(), e);
            return source.toString();
        }
    }

    @Override
    public Object deepCopy(Object object) {
        String json;
        try {
            json = this.mapper.writeValueAsString(object);
            return this.mapper.readValue(json, object.getClass());
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
    }


}
